<template>
  <el-row :gutter="40">
    <el-col :lg="24">
      <el-form :inline="true" :model="queryParams" class="filter-form-inline" label-position="right" size="small">
        <el-row :gutter="40" style="margin-left: 0px; margin-right: 0px">
          <el-col :lg="6" :xs="8">
            <el-form-item label="创建时间" style="width: 100%">
              <date-range-picker v-model:date="queryParams.date" end-placeholder="结束日期" range-separator="至"
                                 start-placeholder="开始日期" style="width: 100%" @change="handlDate"/>
            </el-form-item>
          </el-col>
          <el-col :lg="6" :xs="8">
            <el-form-item label="企业所在地" style="width: 100%">
              <el-cascader v-model="queryParams.value" :options="citys" :popper-append-to-body="false"
                           :props="{ value:'regionCode',label:'regionName' }" clearable placeholder="请选择地区"
                           style="width:100%"
                           @change="handlAreas"/>
            </el-form-item>
          </el-col>
          <el-col :lg="6" :xs="8">
            <el-form-item label="关键字" style="width: 100%">
              <el-input v-model="queryParams.keyWord" clearable placeholder="输入名称、编号、统一社会信用代码、所在地区、详细地址"/>
            </el-form-item>
          </el-col>
          <el-col :lg="6" :xs="8">
            <el-form-item style="width: 100%">
              <el-button class="border-btn" @click="handlReset">重置
              </el-button>
              <el-button class="main-btn" type="primary" @click="handlSearch">搜索
              </el-button>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
    </el-col>
  </el-row>
  <table-view :cell-style="cellStyle" :data="tableData" border header-cell-class-name="table-header" size="medium"
              @sort-change="handlSort" @row-click="aloneClick">
    <el-table-column :show-overflow-tooltip="true" header-align="center" label="代理商编号" prop="agentNumber"/>
    <el-table-column :show-overflow-tooltip="true" header-align="center" label="代理商名称" prop="agentName"/>
    <el-table-column :show-overflow-tooltip="true" align="center" label="企业所在地区" prop="region">
      <template #default="{row}">
        {{ row.provinceName }}/{{ row.cityName }}/{{ row.areaName }}
      </template>
    </el-table-column>
    <el-table-column :show-overflow-tooltip="true" header-align="center" label="创建人" prop="creatorName"/>
    <el-table-column :show-overflow-tooltip="true" align="center" label="创建时间" prop="createdAt" sortable="custom">
      <template #default="{row}">
        {{ dateFormat("yyyy-mm-dd HH:MM:SS", row.createdAt) }}
      </template>
    </el-table-column>
    <el-table-column :show-overflow-tooltip="true" align="center" label="代理状态" prop="terminalStatus">
      <template #default="{row}">
        {{ getLabel('confirmStatus', row.confirmStatus) }}
      </template>
    </el-table-column>
    <el-table-column align="center" label="操作">
      <template #default="{row}">

        <!-- <el-button
            v-auth="{v:['crm:marketing:cooperationInformation:enterprise:delete'],bool:row?.agentStatus === '-1' || row?.agentStatus === '-5' }"
            type="text" @click="handlDelete(row.id)">
          删除
        </el-button> -->

        <el-button v-auth="{v:['crm:marketing:cooperationInformation:enterprise:change'],bool:row.confirmStatus === '0'}" type="text"
                       @click="handlChange(row,1)">
              变更信息
            </el-button>

        <!-- <template v-if="Number(row?.agentStatus) > 1  ">
          <template
              v-if="row.flowStatus !== 'DOING' || row.flowStatus === 'REPEAL' || row.flowStatus === 'REJECT_INITIATOR'">
            <el-button v-auth="{v:['crm:marketing:cooperationInformation:enterprise:change']}" type="text"
                       @click="handlChange(row,1)">
              变更信息
            </el-button>
          </template>
        </template> -->

        <!-- <template v-else>
          <el-button v-auth="{v:['crm:marketing:cooperationInformation:enterprise:change'],
          bool:row?.agentStatus === '-1' ||  row?.agentStatus === '-6' }" type="text" @click="handlChange(row,2)">
            编辑
          </el-button>
        </template> -->

      </template>
    </el-table-column>
  </table-view>
  <Pagination v-model:limit="queryParams.pageSize" v-model:page="queryParams.page"
              :total="total" style="display: flex; justify-content: flex-end" @pagination="handlList"/>
  <!--新建潜在代理商 -->
  <agentDialog ref="agentDialog" :type-title="typeTitle" agent-type="agent" @succsess="succsess"/>
</template>

<script>
import {defineAsyncComponent, getCurrentInstance, inject, onMounted, reactive, toRefs,} from "vue";
import {useRouter} from "vue-router";
import areas from "@/utils/area.js";

export default {
  name: "AgentList",
  components: {
    agentDialog: defineAsyncComponent(() =>
        import("../modules/potentialAgent/agentDialog.vue")
    ),
  },
  setup() {
    const api = inject("api");
    const router = useRouter();
    const currentInstance = getCurrentInstance();
    var data = reactive({
      queryParams: {
        keyWord: "",
        pageSize: 20,
        page: 1,
        date: [],
        startTime: null,
        endTime: null,
        value: "",
        provinceCode: "",
        cityCode: "",
        areaCode: "",
        from: "2",
        tradeStatus: "1",
        agentType: "agent",
      },
      citys: areas,
      tableData: [],
      total: 0,
      agentDialog: null,
      formSign: null,
      typeTitle: "",
    });

    // 新建
    const handlNew = () => {
      data.typeTitle = "新建潜在代理商";
      setTimeout(() => {
        data.agentDialog.open(null);
      }, 100);
    };

    const handlDate = (val) => {
      data.queryParams.startTime = val[0];
      data.queryParams.endTime = val[1];
    };

    const handlAreas = (val) => {
      if (val) {
        data.queryParams.provinceCode = val[0];
        data.queryParams.cityCode = val[1];
        data.queryParams.areaCode = val[2];
      }
    };

    // 获取列表
    const handlList = () => {
      api.channelAgent.POTENTIALAGENT_LIST(data.queryParams).then((res) => {
        if (res.code === 0) {
          data.tableData = res.data.list || [];
          data.total = res.data.total;
        }
      });
    };

    // 刷新列表
    const succsess = () => {
      handlList();
    };

    const succsessFormSign = () => {
      handlList();
    };

    const handlReset = () => {
      data.queryParams = {
        keyWord: "",
        pageSize: 20,
        page: 1,
        date: [],
        startTime: null,
        endTime: null,
        value: "",
        provinceCode: "",
        cityCode: "",
        areaCode: "",
        from: "2",
        tradeStatus: "1",
        agentType: "agent",
      };
      handlList();
    };

    // 搜索
    const handlSearch = () => {
      data.queryParams.page = 1;
      handlList();
    };

    // 单机表格
    const aloneClick = (row, column, event) => {
      if (column.label === "操作" || column.label === "查看文件") return;
      router.push({
        path: "/marketing/cooperationInformation/enterprise/potentialDetail",
        query: {id: row.id},
      });
    };

    // 鼠标样式
    const cellStyle = () => {
      return "cursor:pointer;";
    };

    const handlDelete = (id) => {
      currentInstance.proxy
          .alertBox({message: "删除数据后不可恢复,确定删除？"})
          .then(() => {
            api.channelAgent.POTENTIALAGENT_DELETE_LIST(id).then((res) => {
              if (res.code === 0) {
                currentInstance.proxy.customMessage({
                  type: "success",
                  message: "删除成功",
                });
                handlList();
              } else {
                currentInstance.proxy.customMessage({
                  type: "error",
                  message: res.msg,
                });
              }
            });
          })
          .catch((err) => {
            console.log(err);
          });
    };

    // 变更
    const handlChange = (row, num) => {
      data.typeTitle = "变更潜在代理商";
      setTimeout(() => {
        data.agentDialog.open(row, num);
      }, 100);
    };

    // 排序
    const handlSort = (row) => {
      if (row.column) {
        if (row.column.label === "创建时间") {
          switch (row.order) {
            case "ascending":
              data.queryParams.createdSort = "asc";
              break;
            case "descending":
              data.queryParams.createdSort = "desc";
              break;
          }
        }
      }
      handlList();
    };

    //* **************************************
    onMounted((_) => {
      handlList();
    });
    //* **************************************
    return {
      ...toRefs(data),
      handlReset,
      handlSearch,
      handlNew,
      aloneClick,
      cellStyle,
      handlChange,
      handlDelete,
      handlList,
      succsess,
      succsessFormSign,
      handlSort,
      handlAreas,
      handlDate,
    };
  },
};
</script>

<style scoped>
/* @import url(); 引入css类 */
</style>